
package com.sausageking.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import java.util.logging.Logger;

public class Util {

  private static final Logger log = Logger.getLogger(Util.class.getName());

  public static String encode(final String text) {
    try {
      return URLEncoder.encode(text, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
      throw new IllegalStateException(e);
    }
  }

  public static String fetchURL(final String u) {
    String retStr = "";
    try {
      final URL url = new URL(u);
      final BufferedReader reader = new BufferedReader(new InputStreamReader(
          url.openStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        retStr += line;
      }
      reader.close();
    } catch (final MalformedURLException e) {
      log.warning("MalformedURLException calling url" + u + e);
    } catch (final IOException e) {
      log.warning("IOException calling url" + u + e);
    }
    return retStr;
  }
  
  public static String postToURL(final String url, final String content) {
    String retStr = "";
    try {
      final BufferedReader reader = new BufferedReader(new InputStreamReader(
          new URL(url).openStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        retStr += line;
      }
      reader.close();
    } catch (final MalformedURLException e) {
      log.warning("MalformedURLException calling url" + url + e);
    } catch (final IOException e) {
      log.warning("IOException calling url" + url + e);
    }
    return retStr;
  }
}
